package com.zenithmind.document.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.document.pojo.dto.DocumentShareCreateDTO;
import com.zenithmind.document.pojo.dto.DocumentShareUpdateDTO;
import com.zenithmind.document.pojo.query.DocumentShareQueryDTO;
import com.zenithmind.document.pojo.vo.DocumentShareVO;
import com.zenithmind.document.service.DocumentShareService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 文档分享控制器
 * 遵循单一职责原则：专注于文档分享相关的HTTP接口
 * 遵循依赖倒置原则：依赖抽象服务接口
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/document/share")
@RequiredArgsConstructor
@Validated
@Tag(name = "文档分享管理", description = "文档分享相关接口")
public class DocumentShareController {

    private final DocumentShareService documentShareService;

    @PostMapping
    @Operation(summary = "创建分享", description = "创建文档分享链接")
    public Result<DocumentShareVO> createShare(@Valid @RequestBody DocumentShareCreateDTO createDTO) {
        log.info("创建文档分享请求: documentId={}", createDTO.getDocumentId());
        
        DocumentShareVO result = documentShareService.createShare(createDTO);
        
        return Result.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新分享", description = "更新文档分享信息")
    public Result<Boolean> updateShare(
            @Parameter(description = "分享ID", required = true) @PathVariable @NotBlank String id,
            @Valid @RequestBody DocumentShareUpdateDTO updateDTO) {
        
        log.info("更新文档分享请求: id={}", id);
        
        Boolean result = documentShareService.updateShare(id, updateDTO);
        
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除分享", description = "删除文档分享")
    public Result<Boolean> deleteShare(
            @Parameter(description = "分享ID", required = true) @PathVariable @NotBlank String id) {
        
        log.info("删除文档分享请求: id={}", id);
        
        Boolean result = documentShareService.deleteShare(id);
        
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除分享", description = "批量删除文档分享")
    public Result<Boolean> batchDeleteShares(
            @Parameter(description = "分享ID列表", required = true) @RequestBody @NotEmpty List<String> ids) {
        
        log.info("批量删除文档分享请求: ids={}", ids);
        
        Boolean result = documentShareService.batchDeleteShares(ids);
        
        return Result.success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询分享", description = "分页查询文档分享列表")
    public Result<IPage<DocumentShareVO>> getSharePage(@Valid DocumentShareQueryDTO queryDTO) {
        log.info("分页查询文档分享请求");
        
        IPage<DocumentShareVO> result = documentShareService.getSharePage(queryDTO);
        
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取分享详情", description = "获取文档分享详细信息")
    public Result<DocumentShareVO> getShareDetail(
            @Parameter(description = "分享ID", required = true) @PathVariable @NotBlank String id) {
        
        log.info("获取分享详情请求: id={}", id);
        
        DocumentShareVO result = documentShareService.getShareDetail(id);
        
        return Result.success(result);
    }

    @GetMapping("/code/{shareCode}")
    @Operation(summary = "根据分享码获取分享", description = "根据分享码获取分享信息")
    public Result<DocumentShareVO> getShareByCode(
            @Parameter(description = "分享码", required = true) @PathVariable @NotBlank String shareCode) {
        
        log.info("根据分享码获取分享请求: shareCode={}", shareCode);
        
        DocumentShareVO result = documentShareService.getShareByCode(shareCode);
        
        return Result.success(result);
    }

    @GetMapping("/document/{documentId}")
    @Operation(summary = "获取文档分享列表", description = "获取指定文档的分享列表")
    public Result<List<DocumentShareVO>> getDocumentShares(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId,
            @Parameter(description = "是否包含过期分享") @RequestParam(required = false, defaultValue = "false") Boolean includeExpired) {
        
        log.info("获取文档分享列表请求: documentId={}", documentId);
        
        List<DocumentShareVO> result = documentShareService.getDocumentShares(documentId, includeExpired);
        
        return Result.success(result);
    }

    @GetMapping("/my")
    @Operation(summary = "获取我的分享", description = "获取当前用户的分享列表")
    public Result<List<DocumentShareVO>> getUserShares(
            @Parameter(description = "限制数量") @RequestParam(required = false, defaultValue = "20") Integer limit) {
        
        log.info("获取用户分享列表请求");
        
        String sharerId = UserContext.getUserId();
        List<DocumentShareVO> result = documentShareService.getUserShares(sharerId, limit);
        
        return Result.success(result);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索分享", description = "根据关键词搜索分享")
    public Result<List<DocumentShareVO>> searchShares(
            @Parameter(description = "搜索关键词", required = true) @RequestParam @NotBlank String keyword,
            @Parameter(description = "限制数量") @RequestParam(required = false, defaultValue = "20") Integer limit) {
        
        log.info("搜索分享请求: keyword={}", keyword);
        
        List<DocumentShareVO> result = documentShareService.searchShares(keyword, limit);
        
        return Result.success(result);
    }

    @GetMapping("/hot")
    @Operation(summary = "获取热门分享", description = "获取热门分享列表")
    public Result<List<DocumentShareVO>> getHotShares(
            @Parameter(description = "限制数量") @RequestParam(required = false, defaultValue = "10") Integer limit) {
        
        log.info("获取热门分享请求");
        
        List<DocumentShareVO> result = documentShareService.getHotShares(limit);
        
        return Result.success(result);
    }

    @PostMapping("/validate")
    @Operation(summary = "验证分享访问", description = "验证分享访问权限")
    public Result<Boolean> validateShareAccess(
            @Parameter(description = "分享码", required = true) @RequestParam @NotBlank String shareCode,
            @Parameter(description = "访问密码") @RequestParam(required = false) String password) {
        
        log.info("验证分享访问请求: shareCode={}", shareCode);
        
        Boolean result = documentShareService.validateShareAccess(shareCode, password);
        
        return Result.success(result);
    }

    @PostMapping("/access")
    @Operation(summary = "访问分享", description = "访问分享文档")
    public Result<DocumentShareVO> accessShare(
            @Parameter(description = "分享码", required = true) @RequestParam @NotBlank String shareCode,
            @Parameter(description = "访问密码") @RequestParam(required = false) String password) {
        
        log.info("访问分享请求: shareCode={}", shareCode);
        
        String userId = UserContext.getUserId();
        DocumentShareVO result = documentShareService.accessShare(shareCode, password, userId);
        
        return Result.success(result);
    }

    @GetMapping("/download")
    @Operation(summary = "下载分享文档", description = "下载分享的文档文件")
    public Result<byte[]> downloadSharedDocument(
            @Parameter(description = "分享码", required = true) @RequestParam @NotBlank String shareCode,
            @Parameter(description = "访问密码") @RequestParam(required = false) String password) {
        
        log.info("下载分享文档请求: shareCode={}", shareCode);
        
        String userId = UserContext.getUserId();
        byte[] result = documentShareService.downloadSharedDocument(shareCode, password, userId);
        
        return Result.success(result);
    }

    @PostMapping("/{sourceShareId}/copy")
    @Operation(summary = "复制分享", description = "复制现有分享")
    public Result<DocumentShareVO> copyShare(
            @Parameter(description = "源分享ID", required = true) @PathVariable @NotBlank String sourceShareId,
            @Parameter(description = "新分享标题", required = true) @RequestParam @NotBlank String newTitle) {
        
        log.info("复制分享请求: sourceShareId={}, newTitle={}", sourceShareId, newTitle);
        
        DocumentShareVO result = documentShareService.copyShare(sourceShareId, newTitle);
        
        return Result.success(result);
    }

    @PostMapping("/document/{documentId}/disable")
    @Operation(summary = "禁用文档分享", description = "禁用指定文档的所有分享")
    public Result<Boolean> disableDocumentShares(
            @Parameter(description = "文档ID", required = true) @PathVariable @NotBlank String documentId) {
        
        log.info("禁用文档分享请求: documentId={}", documentId);
        
        Boolean result = documentShareService.disableDocumentShares(documentId);
        
        return Result.success(result);
    }

    @PostMapping("/update-expired")
    @Operation(summary = "更新过期分享", description = "更新过期分享的状态")
    public Result<Integer> updateExpiredShares() {
        log.info("更新过期分享请求");
        
        Integer result = documentShareService.updateExpiredShares();
        
        return Result.success(result);
    }

    @GetMapping("/{shareId}/statistics")
    @Operation(summary = "获取分享统计", description = "获取分享统计信息")
    public Result<DocumentShareVO> getShareStatistics(
            @Parameter(description = "分享ID", required = true) @PathVariable @NotBlank String shareId) {
        
        log.info("获取分享统计请求: shareId={}", shareId);
        
        DocumentShareVO result = documentShareService.getShareStatistics(shareId);
        
        return Result.success(result);
    }

    @GetMapping("/{shareId}/access-logs")
    @Operation(summary = "获取分享访问记录", description = "获取分享访问记录")
    public Result<List<Object>> getShareAccessLogs(
            @Parameter(description = "分享ID", required = true) @PathVariable @NotBlank String shareId,
            @Parameter(description = "限制数量") @RequestParam(required = false, defaultValue = "20") Integer limit) {
        
        log.info("获取分享访问记录请求: shareId={}", shareId);
        
        List<Object> result = documentShareService.getShareAccessLogs(shareId, limit);
        
        return Result.success(result);
    }
}
